package org.luojs.concurrent_test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class CountDownLatchThreadPoolExample {
    private static Random random = new Random();
    private static final int THREAD_POOL_SIZE = 10;
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Integer> list = Arrays.asList(2, 1, 5, 3, 4);
        List<Future<Integer>> futureList = new ArrayList<>();
        List<Integer> results = new ArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(5);

        long startTime = System.currentTimeMillis();

        for (Integer number : list) {
            futureList.add(threadPool.submit(() -> dealNumber(number, countDownLatch)));
        }

        int size = list.size();
        System.out.println("预计处理数量：" + size);

        long dealTime = System.currentTimeMillis();

        countDownLatch.await();
        // 等待异步任务完成并输出结果
        for (Future<Integer> future : futureList) {
            results.add(future.get());
        }
        System.out.println(results);

        long endTime = System.currentTimeMillis();

        System.out.println(dealTime - startTime);
        System.out.println(endTime - startTime);

        // 关闭线程池
        threadPool.shutdown();
    }

    private static int dealNumber(int source, CountDownLatch countDownLatch) {
        try {
            int i = random.nextInt(5) + 1;
            System.out.println("计算延时：" + i);
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        countDownLatch.countDown();
        return source * 10;
    }
}
